﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Skyworth.CRM.Common;
using Skyworth.CRM.Service.IBLL;
using Skyworth.CRM.Service.Entity;

namespace Skyworth.CRM.Web.SystemManagement
{
    public partial class UserCommision : BasePage
    {
        private IModulesBLL modulesBLL = IocContainer.Instance.Resolve<IModulesBLL>();
        private IUserBLL userBLL = IocContainer.Instance.Resolve<IUserBLL>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    BinDropDownList<DropDownList>(ddlModules, modulesBLL.GetModules(), "", "");
                    if (!string.IsNullOrEmpty(Request.QueryString["UserId"]))
                    {
                        labUserName.Text = Request.QueryString["UserName"];
                        this.txtUserId.Value = Request.QueryString["UserId"];
                        BindPages(Convert.ToInt32(this.ddlModules.SelectedValue), Convert.ToInt32(txtUserId.Value));
                    }
                }
                catch (Exception ex)
                {
                    Logger.Instance.Error(ex);
                    Alert("发生异常：\r\n" + ex.Message);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                IList<UserModules> list = new List<UserModules>();
                int userId = Convert.ToInt32(this.txtUserId.Value);
                int modelId = Convert.ToInt32(this.ddlModules.SelectedValue);
                for (int i = 0; i < this.gvModuleView.Rows.Count; i++)
                {
                    Label lblMenu = (Label)this.gvModuleView.Rows[i].Cells[0].FindControl("lab_ID");
                    CheckBoxList chk = (CheckBoxList)this.gvModuleView.Rows[i].Cells[1].FindControl("AuthorityList");
                    int pageId = Convert.ToInt32(lblMenu.Text);
                    for (int j = 0; j < chk.Items.Count; j++)
                    {
                        ListItem item = chk.Items[j];
                        bool temp = item.Selected;
                        UserModules userPage = new UserModules();
                        userPage.UserID = userId;
                        userPage.ModuleID = pageId;
                        userPage.FunctionID = Convert.ToInt32(item.Value);
                        userPage.Flag = temp;
                        list.Add(userPage);
                    }
                }
                if (list.Count > 0)
                {
                    userBLL.SetUserAuthority(modelId, list);
                    Alert("设置用户权限完成！");
                }
                else
                {
                    Alert("模块对应页面至少要存在一个！");
                }
            }
            catch (Exception exception)
            {
                Logger.Instance.Error(exception);
                Alert("发生异常：\r\n" + exception.Message);
            }
        }

        protected void BindPages(int moduleId, int userId)
        {
            try
            {
                DataTable dtModules = modulesBLL.GetPagesAuthorityByUser(moduleId, userId);
                this.gvModuleView.DataSource = dtModules;
                this.gvModuleView.DataBind();
            }
            catch (Exception ex)
            {
                Logger.Instance.Error(ex);
                Alert("发生异常：\r\n" + ex.Message);
            }
        }

        protected void ModuleView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                try
                {
                    CheckBoxList AuthorityList = (CheckBoxList)e.Row.FindControl("AuthorityList");
                    Label menu_ID = (Label)e.Row.FindControl("lab_ID");
                    string menuId = this.gvModuleView.DataKeys[e.Row.RowIndex]["ModuleID"].ToString();
                    string pages = this.gvModuleView.DataKeys[e.Row.RowIndex]["pageAuthority"].ToString();
                    DataTable PageData = IocContainer.Instance.Resolve<IFunctionBLL>().GetPagesFunction(Convert.ToInt32(menuId));
                    //获取系统配置的权限列表，如果模块没有该权限,则禁用该权限
                    for (int i = 0; i < PageData.Rows.Count; i++)
                    {
                        string functionID = PageData.Rows[i]["FunctionID"].ToString();
                        string functionName = PageData.Rows[i]["FunctionName"].ToString();
                        AuthorityList.Items.Add(new ListItem(functionName, functionID));
                        AuthorityList.Items[i].Enabled = Convert.ToBoolean(PageData.Rows[i]["flag"]);
                        AuthorityList.Items[i].Selected = ((IList<String>)pages.Split(',')).Contains(functionID);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Instance.Error(ex);
                    Alert("发生异常：\r\n" + ex.Message);
                }
            }
        }

        protected void ddlModules_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindPages(Convert.ToInt32(this.ddlModules.SelectedValue), Convert.ToInt32(txtUserId.Value));
        }
    }
}